<?php

namespace User\Model;
use Common\Model\CommonModel;

/**
 * @description 宜信致诚阿福接口模型
 * Class UserZcaf
 */
class UserZcaf extends CommonModel {

    protected $trueTableName = 'system_user_zcaf';
    protected $dbName = 'nuonuo';
    protected  $connection = 'DB_CONFIG2';

    //https 方式内容几乎全都是明文，http 方式的内容则是部分或者全部的加密内容。
    private $http_base_url = 'http://www.zhichengcredit.com/echo-center/api/echoApi/v3';
    private $https_base_url = 'https://www.zhichengcredit.com/echo-center/api/echoApi/v3';
    private $base_url = 'http';
    private $RC4_KEY;

    private $config;

    /**
     * 查询原因 queryReason
     * queryReason 的取值范围是：10、11、12、13、14，含义如下
     * 10  贷款审批
     * 11  贷后管理
     * 12  信用卡审批
     * 13  担保资格审查
     * 14  保前审查
     */

    public function __construct($http_method='http'){
        parent::__construct();
        /**
         * //编码格式utf8
         * http参数:userid,params
         * https参数:sign,userid,params
         * https 方式的 params 参数内容是没有经过任何处理的 json。data 节点的内容因业务的不同而异。下面介绍的是每个业务 data 的具体格式。
         *
         * sign 用户名和密码无缝有序连接后的结果做MD5 并转换成 16 进制输出。【http 无此参数】
         * userid  致诚公钥加密的用户名  用户名明文经过致诚公钥加密
         * params  Json 格式的查询内容经 RC4 密钥加密后 查询内容被加密了
         */
        //判断请求方式
        if('http'==$http_method){
            $this->base_url = $this->http_base_url;
        }else{
            $this->base_url = $this->https_base_url;
        }
        $this->config = C('YX_CONFIG');
    }


    //TODO 测试方法
    public function testAF($name,$idNo){
        $params = [
            'tx'    =>  '101',
            'data'    =>  [
                'name'  =>  $name,
                'idNo'  =>  $idNo,
                'queryReason'  =>  '10',
            ],
        ];
        $output_arr = $this->echoCurlGetDate($params);
        return $output_arr;
    }

    /**
     * 加密致诚userid
     * @param $user_id
     * @param $zc_public_key 致诚公钥
     * @return string
     */
    private function encrypt_userid($user_id){
//        $proj_base_dir = dirname(dirname(dirname(__FILE__)));
//        $rsa_file = $proj_base_dir.'/lib/zc_rsa_file/ZC_PublicKey_V2.pem';
        //1) 用致诚提供的公钥对 userid 的内容做 RSA 加密，得到加密结果 E；
//        $file_content = file_get_contents($rsa_file);
        $file_content = "-----BEGIN PUBLIC KEY----- 
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgFrw0sOBUJ1mXFvIihpB1qlEflFWD8A7MzxAH
ms98QbST1vi3pjKwigWpDKOCDPhgSuXr6o5R9T8kTqqYzwPX8ZphvUEzZwOiVnlIiQgERg3CALvV
dinu7KkG224LwOMZMCDNZYQSy6SDueVg/OSteu05OsE/pLlKwvkVEFjR4wIDAQAB
-----END PUBLIC KEY----- ";
        $result_E = '';
        $pu_key = openssl_pkey_get_public($file_content);//读取公钥文件
        openssl_public_encrypt($user_id,$result_E,$pu_key);//公钥加密
        //2) 对 RSA 公钥加密结果 E 做 Base64 编码，得到编码结果 EB；
        $result_EB = base64_encode($result_E);
        //3) 对 Base64 编码结果 EB 做 URLEncode（将其中的特殊字符做转义），得到结果 EBU
        $result_EBU = urlencode($result_EB);
        //参数 userid 对应的内容就是 EBU。
        return $result_EBU;
    }

    /**
     * 加密致诚params
     * @param $params
     * @return string
     */
    private function encrypt_params($params){
        $config = $this->config;
        //1) 用致诚提供的 RC4 对称密钥对 params 的内容（json 串）做对称加密，得到结果 E；
        $result_E = rc4_encode($config['RC4_KEY'],$params);
        //2) 对 RC4 对称加密的结果 E 做 Base64 编码，得到编码结果 EB；
        $result_EB = base64_encode($result_E);
        //3) 对 Base64 编码结果 EB 做 URLEncode，得到结果 EBU；
        $result_EBU = urlencode($result_EB);
        //参数 params 对应的内容就是上述过程产生的 EBU。
        return $result_EBU;
    }

    /**
     * 致诚-获取数据 请求方式:同一链接地址+POST提交请求参数
     * @param string $http_method
     * @param $params
     * @return mixed
     */
    private function echoCurlGetDate($params){
        $param_arr = [
            'params'    => $this->encrypt_params(json_encode($params)),
            'userid'    =>  $this->encrypt_userid($this->config['ACCOUNT']),
        ];
        //初始化
        $ch = curl_init();
        //        //设置选项，包括URL
        $this_header = array(
            "content-type: application/x-www-form-urlencoded;charset=GB2312"
        );
        // 发送请求
        $data = $param_arr;
        curl_setopt ($ch, CURLOPT_URL, $this->base_url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$this_header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $json_data = curl_exec($ch);
        //解析返回结果（json格式字符串）
        $array = json_decode($json_data,true);
        $array['params'] = $this->parseResult($array['params']);
        return $array;
    }

    /**
     * 解析查询结果-解码
     * 当要取得 params内容原文时，需要对 params 内容做逆序操作，即 URLDecode、Base64 解码、RC4 解密。
     * @param $result_params
     */
    public function parseResult($result_params){
        $config = $this->config;
        $result_EB = urldecode($result_params);
        $result_E = base64_decode($result_EB);
        $result = rc4_encode($config['RC4_KEY'],$result_E);;
        return $result;
    }

    /**
     * 保存数据到数据库
     * @param $user_id 用户信息Id
     * @param $result_set 查询结果集
     */
    public function saveDate2Db($user_id,$result_set){
        $result_set = json_decode($result_set,true);
        $result_set = $result_set['data'];
        $result_statistics = $result_set['queryStatistics'];//被查询统计
        $result_queryHistory = $result_set['queryHistory'];//被查询历史
        $result_loanRecords = $result_set['loanRecords'];//借款记录历史
        $result_riskResults = $result_set['riskResults'];//风险项记录
        //添加查询基本信息+被查询统计
        $data['user_id'] = $user_id;
        $data['zcCreditScore'] = $result_set['zcCreditScore'];
        $data['contractBreakRate'] = $result_set['contractBreakRate'];
        $data['timesByOtherOrg'] = $result_statistics['timesByOtherOrg'];
        $data['otherOrgCount'] = $result_statistics['otherOrgCount'];
        $data['timesByCurrentOrg'] = $result_statistics['timesByCurrentOrg'];
        $data['crtime'] = time();
        $where['user_id'] = $user_id;
        $record = $this->where($where)->find();
        if(empty($record)){//插入
            $zcaf_id = $this->add($data);
        }else{
            $zcaf_id = $record['id'];
        }

        //添加被查询历史
        if(!empty($result_queryHistory)&&!empty($zcaf_id)){
            $ht_data = [];
            foreach ($result_queryHistory AS $key=>$val){
                $obj['user_id'] = $user_id;
                $obj['zcaf_id'] = $zcaf_id;
                $obj['orgName'] = $val['orgName'];
                $obj['time'] = $val['time'];
                $obj['orgType'] = $val['orgType'];
                $obj['queryReason'] = $val['queryReason'];
                array_push($ht_data,$obj);
            }
            $ht_filed = ['user_id','zcaf_id','orgName','time','orgType','queryReason'];
            $ht_sql = array_to_insert_sql('system_user_zcaf_history',$ht_filed,$ht_data).' ON DUPLICATE KEY UPDATE updatetime='.time().';';
            $this->execute($ht_sql);
        }
        //添加借款记录历史
        if(!empty($result_loanRecords)&&!empty($zcaf_id)){
            foreach ($result_loanRecords AS $key=>$val){
                $obj2['user_id'] = $user_id;
                $obj2['zcaf_id'] = $zcaf_id;
                $obj2['name'] = $val['name'];
                $obj2['orgName'] = $val['orgName'];
                $obj2['certNo'] = $val['certNo'];
                $obj2['loanDate'] = $val['loanDate'];
                $obj2['periods'] = $val['periods'];
                $obj2['loanAmount'] = $val['loanAmount'];
                $obj2['approvalStatusCode'] = $val['approvalStatusCode'];
                $obj2['loanStatusCode'] = $val['loanStatusCode'];
                $obj2['loanTypeCode'] = $val['loanTypeCode'];
                $obj2['overdueAmount'] = $val['overdueAmount'];
                $obj2['overdueStatus'] = $val['overdueStatus'];
                $obj2['overdueTotal'] = $val['overdueTotal'];
                $obj2['overdueM3'] = $val['overdueM3'];
                $obj2['overdueM6'] = $val['overdueM6'];
                $obj2['updatetime'] = time();
                array_push($lr_data,$obj2);
            }
            $lr_filed = ['user_id','zcaf_id','orgName','certNo','loanDate','periods','loanAmount','approvalStatusCode',
                'loanStatusCode','loanTypeCode','overdueAmount','overdueStatus','overdueTotal','overdueM3','overdueM6'];
            $lr_sql = array_to_insert_sql('system_user_zcaf_records',$lr_filed,$lr_data).' ON DUPLICATE KEY UPDATE updatetime'.time().';';
            $this->execute($lr_sql);
        }
        //添加风险项记录
        if(!empty($result_riskResults)&&!empty($zcaf_id)){
            $rr_data = [];
            foreach ($result_riskResults AS $key=>$val){
                $obj3['user_id'] = $user_id;
                $obj3['zcaf_id'] = $zcaf_id;
                $obj3['orgName'] = $val['orgName'];
                $obj3['riskItemTypeCode'] = $val['riskItemTypeCode'];
                $obj3['riskItemValue'] = $val['riskItemValue'];
                $obj3['riskTypeCode'] = $val['riskTypeCode'];
                $obj3['riskDetail'] = $val['riskDetail'];
                $obj3['riskTime'] = $val['riskTime'];
                array_push($rr_data,$obj3);
            }
            $rr_filed = ['user_id','zcaf_id','orgName','riskItemTypeCode','riskItemValue','riskTypeCode','riskDetail','riskTime'];
            $rr_sql = array_to_insert_sql('system_user_zcaf_risk',$rr_filed,$rr_data).' ON DUPLICATE KEY UPDATE updatetime='.time().';';;
            $this->execute($rr_sql);
        }
        return array('code'=>0,'msg'=>'操作成功');
    }

    /**
     * 查询用户数据并保存到数据库
     * @param $user_id 用户Id
     * @param $name 用户名称
     * @param $idNo 身份证号
     */
    public function checkAndSaveDate($user_id,$name,$idNo){
        $params = [
            'tx'    =>  '101',
            'data'    =>  [
                'name'  =>  $name,
                'idNo'  =>  $idNo,
                'queryReason'  =>  '10',
            ],
        ];
        $output_arr = $this->echoCurlGetDate($params);
        if(!empty($output_arr['params'])){
            $this->saveDate2Db($user_id,$output_arr['params']);
        }
        return $output_arr;
    }

    /**
     * 致诚查询存在90天以上逾期
     * 使用字段：“90天以上逾期次数”
     * @param $name
     * @param $idNo
     * @return mixed
     */
    public function check_yu_morethan90($name,$idNo){
        $params = [
            'tx'    =>  '101',
            'data'    =>  [
                'name'  =>  $name,
                'idNo'  =>  $idNo,
                'queryReason'  =>  '10',
            ],
        ];
        $output_arr = $this->echoCurlGetDate($params);
        $flag = false;
        return $output_arr;
    }

    /**
     * 致诚查询存在180天以上逾期
     * 使用字段：“180天以上逾期次数”
     * @param $name
     * @param $idNo
     * @return mixed
     */
    public function check_yu_morethan180($name,$idNo){
        $params = [
            'tx'    =>  '101',
            'data'    =>  [
                'name'  =>  $name,
                'idNo'  =>  $idNo,
                'queryReason'  =>  '10',
            ],
        ];
        $output_arr = $this->echoCurlGetDate($params);
        $params = json_decode($output_arr['params'],true);
        $result_riskResults = $params['loanRecords'];//借款记录
        return [
            'errorCode' =>  0,
            'message'   =>  '',
            'risk_result'=>  $result_riskResults,
        ];
    }

    /**
     * 致诚查询存在风险名单
     * 使用字段：“风险名单查询”
     * @param $name
     * @param $idNo
     * @return array [risk_result:风险列表]
     */
    public function check_risk_user($name,$idNo){
        $params = [
            'tx'    =>  '101',
            'data'    =>  [
                'name'  =>  $name,
                'idNo'  =>  $idNo,
                'queryReason'  =>  '10',
            ],
        ];
        $output_arr = $this->echoCurlGetDate($params);
        $params = json_decode($output_arr['params'],true);
        $result_riskResults = $params['riskResults'];//风险名单查询
        return [
            'errorCode' =>  0,
            'message'   =>  '',
            'risk_result'=>  $result_riskResults,
        ];
    }

    /**
     * 致诚查询到借款申请次数大于5
     * 使用字段：“借款记录集合”的条数
     * @param $name
     * @param $idNo
     * @return array [loan_count:借款次数]
     */
    public function check_borrow_time_morethan5($name,$idNo){
        $params = [
            'tx'    =>  '101',
            'data'    =>  [
                'name'  =>  $name,
                'idNo'  =>  $idNo,
                'queryReason'  =>  '10',
            ],
        ];
        $output_arr = $this->echoCurlGetDate($params);
        $params = json_decode($output_arr['params'],true);
        $result_loanRecords = $params['loanRecords'];//借款记录历史
        $loan_count = count($result_loanRecords);
        return [
            'errorCode' =>  0,
            'message'   =>  '',
            'loan_count'=>  empty($result_loanRecords)?0:$loan_count,
        ];
    }

}

?>